
package x2rel.qMap.logger;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

import org.springframework.web.util.HtmlUtils;

class LogHtmlFormatter extends Formatter
{

    public String format(LogRecord rec){

        StringBuffer buf = new StringBuffer(1000);

        buf.append("<tr>");
        buf.append("<td>");

    if (rec.getLevel().intValue() >= Level.WARNING.intValue()){
        
        buf.append("<b>");
        buf.append(rec.getLevel());
        buf.append("</b>");
        
    } else {
        
      buf.append(rec.getLevel());
      
    }
    
    buf.append("</td>");
    buf.append("<td>");
    buf.append(calcDate(rec.getMillis()));
    buf.append("</td><td>");
    if (rec.getLevel().intValue() >= Level.WARNING.intValue()){
        buf.append("<pre class=\"raw\">");
    }else{
        buf.append("<pre>");
    }
    
    buf.append(HtmlUtils.htmlEscape(formatMessage(rec)));
    buf.append('\n');
    buf.append("</pre></td>");
    buf.append("</tr>\n");
    
    return buf.toString();
    
  }

  private String calcDate(long millisecs){

    SimpleDateFormat date_format = new SimpleDateFormat("yyyy/mm/dd HH:mm");
    Date resultdate = new Date(millisecs);
    
    return date_format.format(resultdate);
    
  }

  
  public String getHead(Handler h){
      
    return "<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n" + (new Date()) + "\n"
            + "<script src=\"http://code.jquery.com/jquery-latest.js\"></script>"
            + "<script src=\"js/beautify.js\"></script>"
            + "<script src=\"js/beautify-html.js\"></script>"
            + "<script src=\"js/mybeautifier.js\"></script>"
            + "<script type=\"text/javascript\">    $(document).ready(function() {      $('.raw').each(function()      {          /*  console.log(this); */        beautify(this);      });  });</script>"
            + "</HEAD>\n<BODY>\n"
        + "<table border>\n  "
        + "<tr><th>Tipo</th><th>Hora</th><th>Mensagem</th></tr>\n";
    
  }

  
  public String getTail(Handler h){
      
    return "</table>\n  </BODY>\n</HTML>\n";
    
  }
  
} 